package controlador;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelo.bd.excepcion.DAOException;
import modelo.dominio.Factura;
import modelo.servicio.Facturas;
import modelo.servicio.util.Formateador;

public class FacturaControlador extends HttpServlet {

    private String accion;
    private String usuario;
    private StringBuilder html;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        html = new StringBuilder("");
        accion = request.getParameter("ac") != null
                ? request.getParameter("ac") : "";
        usuario = request.getSession().getAttribute("sUsuario") != null
                ? request.getSession().getAttribute("sUsuario").toString() : "";
        try {
            if (accion.compareToIgnoreCase("ls") == 0) {
            } else if (accion.compareToIgnoreCase("sv") == 0) {
            } else if (accion.compareToIgnoreCase("ed") == 0) {
            } else if (accion.compareToIgnoreCase("op") == 0) {
                String proveedor = request.getParameter("prpo");
                List<Factura> facturas = Facturas.instancia().obtenerR12(proveedor);
                generarOpcionesFactura(facturas);
            } else if (accion.compareToIgnoreCase("de") == 0) {
                String folioFactura = request.getParameter("folio");
                Factura factura = Facturas.instancia().porFolioR12(folioFactura);
                DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
                html.append("<script type='text/javascript'>");
                html.append("$('input[name=txt_folio_fact]').val('").append(factura.getFolio()).append("');");
                html.append("$('input[name=txt_monto_fact]').val('").append(Formateador.moneda(factura.getMonto(), false)).append("');");
                html.append("$('input[name=txt_fecha_fact]').val('").append(df.format(factura.getFacturacion())).append("');");
                html.append("$('textarea[name=txa_concepto]').val('").append(factura.getConcepto()).append("');");
                html.append("</script>");
            }
            out.println(html);
        } catch (DAOException dex) {
            out.println("Error en la base de datos: " + dex.getMessage() + "<br/>" + dex.getLocalizedMessage());
        } finally {
            out.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    private void generarOpcionesFactura(List<Factura> facturas) {
        if (!facturas.isEmpty()) {
            html.append("<td><strong><font color='red'>*</font> Factura: </strong></td><td>");
            html.append("<select name='cmb_factura' id='cmb_factura'>");
            html.append("<option value='0'>Selecciona Factura</option>");
            for (Factura factura : facturas) {
                html.append("<option value='").append(factura.getFolio()).append("'>");
                html.append(factura.getFolio()).append(" - ");
                if (factura.getConcepto().length() > 30) {
                    html.append(factura.getConcepto().substring(0, 30));
                } else {
                    html.append(factura.getConcepto());
                }
                html.append(" (").append(Formateador.moneda(factura.getMonto(), true)).append(")");
                html.append("</option>");
            }
            html.append("<script type='text/javascript'>");
            html.append("$('#cmb_factura').change(function(){");
            html.append("$('input[name=txt_folio_fact]').val('');");
            html.append("$('input[name=txt_monto_fact]').val('');");
            html.append("$('input[name=txt_fecha_fact]').val('');");
            html.append("$('textarea[name=txa_concepto]').val('');");
            html.append("   var factura = $('#cmb_factura').val();");
            html.append("   charge('#trash', 'fact?ac=de&folio='+factura); ");
            html.append("});</script>");
            html.append("</select></td>");
        }
    }
}
